<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar 
      :title="isEdit ? '编辑会员' : '会员详情'" 
      left-icon="back" 
      :right-text="isEdit ? '保存' : '编辑'"
      @clickLeft="handleBack"
      @clickRight="handleRightAction"
      background-color="#2979FF"
      color="#fff"
    />

    <scroll-view scroll-y class="content-scroll">
      <!-- 会员基础信息卡片 -->
      <uni-card title="基础信息" :is-shadow="true" margin="15px 15px 0">
        <view class="member-info-card">
          <view class="avatar-section">
            <image 
              class="member-avatar" 
              :src="memberInfo.avatar || '/static/images/avatar-placeholder.png'" 
              mode="aspectFill"
              @click="handleAvatarClick"
            />
            <view v-if="isEdit" class="avatar-edit-btn" @click="handleAvatarClick">
              <uni-icons type="camera" size="16" color="#fff" />
            </view>
          </view>
          
          <view class="info-section">
            <view class="info-row">
              <text class="info-label">姓名</text>
              <uni-easyinput 
                v-if="isEdit"
                v-model="editForm.name" 
                placeholder="请输入姓名"
                :clearable="false"
              />
              <text v-else class="info-value">{{ memberInfo.name || '-' }}</text>
            </view>
            
            <view class="info-row">
              <text class="info-label">手机号</text>
              <uni-easyinput 
                v-if="isEdit"
                v-model="editForm.phone" 
                placeholder="请输入手机号"
                type="number"
                :clearable="false"
              />
              <text v-else class="info-value">{{ memberInfo.phone || '-' }}</text>
            </view>
            
            <view class="info-row">
              <text class="info-label">邮箱</text>
              <uni-easyinput 
                v-if="isEdit"
                v-model="editForm.email" 
                placeholder="请输入邮箱"
                :clearable="false"
              />
              <text v-else class="info-value">{{ memberInfo.email || '-' }}</text>
            </view>
            
            <view class="info-row">
              <text class="info-label">会员等级</text>
              <uni-data-select 
                v-if="isEdit"
                v-model="editForm.level_id"
                :localdata="levelOptions"
                placeholder="请选择会员等级"
              />
              <view v-else class="level-display">
                <uni-tag 
                  :text="getLevelName(memberInfo.level_id)" 
                  :type="getLevelType(memberInfo.level_id)"
                  size="small"
                />
              </view>
            </view>
            
            <view class="info-row">
              <text class="info-label">状态</text>
              <uni-data-select 
                v-if="isEdit"
                v-model="editForm.status"
                :localdata="statusOptions"
                placeholder="请选择状态"
              />
              <view v-else class="status-display">
                <uni-tag 
                  :text="memberInfo.status === 1 ? '正常' : '禁用'" 
                  :type="memberInfo.status === 1 ? 'success' : 'error'"
                  size="small"
                />
              </view>
            </view>
            
            <view class="info-row">
              <text class="info-label">备注</text>
              <uni-easyinput 
                v-if="isEdit"
                v-model="editForm.description" 
                type="textarea"
                placeholder="请输入备注"
                :clearable="false"
              />
              <text v-else class="info-value">{{ memberInfo.description || '-' }}</text>
            </view>
          </view>
        </view>
      </uni-card>

      <!-- 余额积分展示区 -->
      <view class="balance-points-section">
        <uni-card title="余额" :is-shadow="true" margin="15px 7.5px 0 15px">
          <view class="balance-card">
            <view class="amount-display">
              <text class="amount-value">¥{{ (memberInfo.balance / 100).toFixed(2) }}</text>
              <text class="amount-label">账户余额</text>
            </view>
            <button 
              class="adjust-btn" 
              size="mini" 
              @click="handleAdjustBalance"
            >
              调整余额
            </button>
          </view>
        </uni-card>
        
        <uni-card title="积分" :is-shadow="true" margin="15px 15px 0 7.5px">
          <view class="points-card">
            <view class="amount-display">
              <text class="amount-value">{{ memberInfo.points || 0 }}</text>
              <text class="amount-label">当前积分</text>
            </view>
            <button 
              class="adjust-btn" 
              size="mini" 
              @click="handleAdjustPoints"
            >
              调整积分
            </button>
          </view>
        </uni-card>
      </view>

      <!-- 功能操作区 -->
      <uni-card title="功能操作" :is-shadow="true" margin="15px">
        <view class="function-grid">
          <view class="function-item" @click="navigateToBalanceLog">
            <uni-icons type="wallet" size="24" color="#2979FF" />
            <text class="function-text">余额记录</text>
          </view>
          <view class="function-item" @click="navigateToPointsLog">
            <uni-icons type="gift" size="24" color="#2979FF" />
            <text class="function-text">积分记录</text>
          </view>
          <view class="function-item" @click="navigateToMemberCard">
            <uni-icons type="vip" size="24" color="#2979FF" />
            <text class="function-text">会员卡管理</text>
          </view>
          <view class="function-item" @click="handleStatusManagement">
            <uni-icons type="settings" size="24" color="#2979FF" />
            <text class="function-text">状态管理</text>
          </view>
        </view>
      </uni-card>

      <!-- 统计信息 -->
      <uni-card title="统计信息" :is-shadow="true" margin="15px">
        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-label">注册时间</text>
            <text class="stat-value">{{ formatDate(memberInfo.created_at) }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">最后登录</text>
            <text class="stat-value">{{ formatDate(memberInfo.last_login_at) }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">最后消费</text>
            <text class="stat-value">{{ formatDate(memberInfo.last_consume_time) }}</text>
          </view>
          <view class="stat-item">
            <text class="stat-label">消费次数</text>
            <text class="stat-value">{{ memberInfo.consume_count || 0 }}次</text>
          </view>
        </view>
      </uni-card>
    </scroll-view>

    <!-- 调整余额弹窗 -->
    <uni-popup ref="balancePopupRef" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="调整余额"
        :before-close="true"
        @confirm="confirmAdjustBalance"
        @close="closeBalancePopup"
      >
        <template #default>
          <view class="adjust-popup-content">
            <view class="current-info">
              <text class="current-label">当前余额</text>
              <text class="current-value">¥{{ (memberInfo.balance / 100).toFixed(2) }}</text>
            </view>
            
            <view class="adjust-form">
              <uni-forms ref="balanceFormRef" :modelValue="balanceForm" :rules="balanceRules">
                <uni-forms-item label="调整类型" name="type" required>
                  <uni-data-checkbox 
                    v-model="balanceForm.type" 
                    :localdata="balanceTypeOptions"
                    mode="button"
                  />
                </uni-forms-item>
                
                <uni-forms-item label="调整金额" name="amount" required>
                  <uni-easyinput 
                    v-model="balanceForm.amount" 
                    type="digit" 
                    placeholder="请输入金额"
                  />
                </uni-forms-item>
                
                <uni-forms-item label="调整原因" name="description" required>
                  <uni-easyinput 
                    v-model="balanceForm.description" 
                    type="textarea" 
                    placeholder="请输入调整原因"
                  />
                </uni-forms-item>
              </uni-forms>
            </view>
          </view>
        </template>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 调整积分弹窗 -->
    <uni-popup ref="pointsPopupRef" type="dialog">
      <uni-popup-dialog
        mode="input"
        title="调整积分"
        :before-close="true"
        @confirm="confirmAdjustPoints"
        @close="closePointsPopup"
      >
        <template #default>
          <view class="adjust-popup-content">
            <view class="current-info">
              <text class="current-label">当前积分</text>
              <text class="current-value">{{ memberInfo.points || 0 }}</text>
            </view>
            
            <view class="adjust-form">
              <uni-forms ref="pointsFormRef" :modelValue="pointsForm" :rules="pointsRules">
                <uni-forms-item label="调整类型" name="type" required>
                  <uni-data-checkbox 
                    v-model="pointsForm.type" 
                    :localdata="pointsTypeOptions"
                    mode="button"
                  />
                </uni-forms-item>
                
                <uni-forms-item label="调整积分" name="points" required>
                  <uni-easyinput 
                    v-model="pointsForm.points" 
                    type="number" 
                    placeholder="请输入积分"
                  />
                </uni-forms-item>
                
                <uni-forms-item label="调整原因" name="description" required>
                  <uni-easyinput 
                    v-model="pointsForm.description" 
                    type="textarea" 
                    placeholder="请输入调整原因"
                  />
                </uni-forms-item>
              </uni-forms>
            </view>
          </view>
        </template>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { fetchMemberDetail, updateMember, adjustMemberBalance, adjustMemberPoints } from '@/api/member';
import type { Member } from '@/types/member';

interface EditForm {
  name: string;
  phone: string;
  email: string;
  level_id: number | undefined;
  status: number;
  description: string;
}

interface BalanceForm {
  type: string;
  amount: string;
  description: string;
}

interface PointsForm {
  type: string;
  points: string;
  description: string;
}

const memberId = ref<number | null>(null);
const isEdit = ref(false);
const memberInfo = ref<Member>({} as Member);
const balancePopupRef = ref<any>(null);
const pointsPopupRef = ref<any>(null);
const balanceFormRef = ref<any>(null);
const pointsFormRef = ref<any>(null);

const editForm = reactive<EditForm>({
  name: '',
  phone: '',
  email: '',
  level_id: undefined,
  status: 1,
  description: '',
});

const balanceForm = reactive<BalanceForm>({
  type: 'add',
  amount: '',
  description: '',
});

const pointsForm = reactive<PointsForm>({
  type: 'add',
  points: '',
  description: '',
});

// 会员等级选项
const levelOptions = ref([
  { value: 1, text: '普通会员' },
  { value: 2, text: '银卡会员' },
  { value: 3, text: '金卡会员' },
  { value: 4, text: '钻石会员' },
]);

// 状态选项
const statusOptions = [
  { value: 1, text: '正常' },
  { value: 0, text: '禁用' },
];

// 余额调整类型选项
const balanceTypeOptions = [
  { value: 'add', text: '增加' },
  { value: 'subtract', text: '减少' },
];

// 积分调整类型选项
const pointsTypeOptions = [
  { value: 'add', text: '增加' },
  { value: 'subtract', text: '减少' },
];

// 表单验证规则
const balanceRules = {
  type: { rules: [{ required: true, errorMessage: '请选择调整类型' }] },
  amount: { 
    rules: [
      { required: true, errorMessage: '请输入调整金额' },
      { pattern: /^\d+(\.\d{1,2})?$/, errorMessage: '请输入有效的金额' }
    ] 
  },
  description: { rules: [{ required: true, errorMessage: '请输入调整原因' }] },
};

const pointsRules = {
  type: { rules: [{ required: true, errorMessage: '请选择调整类型' }] },
  points: { 
    rules: [
      { required: true, errorMessage: '请输入调整积分' },
      { pattern: /^\d+$/, errorMessage: '请输入有效的积分' }
    ] 
  },
  description: { rules: [{ required: true, errorMessage: '请输入调整原因' }] },
};

// 获取会员等级名称
const getLevelName = (levelId: number) => {
  const level = levelOptions.value.find(item => item.value === levelId);
  return level ? level.text : '未知等级';
};

// 获取会员等级类型
const getLevelType = (levelId: number) => {
  const typeMap: { [key: number]: string } = {
    1: 'default',
    2: 'primary',
    3: 'warning',
    4: 'error',
  };
  return typeMap[levelId] || 'default';
};

// 格式化日期
const formatDate = (timestamp: number) => {
  if (!timestamp) return '-';
  const date = new Date(timestamp * 1000);
  return date.toLocaleString('zh-CN');
};

// 获取会员详情
const getMemberDetail = async () => {
  if (!memberId.value) return;
  
  try {
    uni.showLoading({ title: '加载中...' });
    const res = await fetchMemberDetail(memberId.value);
    memberInfo.value = res;
    
    // 初始化编辑表单
    Object.assign(editForm, {
      name: res.name || '',
      phone: res.phone || '',
      email: res.email || '',
      level_id: res.level_id || null,
      status: res.status || 1,
      description: res.description || '',
    });
  } catch (error: any) {
    uni.showToast({
      title: error.message || '获取会员详情失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 处理返回
const handleBack = () => {
  if (isEdit.value) {
    uni.showModal({
      title: '提示',
      content: '是否放弃编辑？',
      success: (res) => {
        if (res.confirm) {
          isEdit.value = false;
          // 重置表单
          getMemberDetail();
        }
      }
    });
  } else {
    uni.navigateBack();
  }
};

// 处理右侧按钮点击
const handleRightAction = async () => {
  if (isEdit.value) {
    // 保存编辑
    await handleSaveEdit();
  } else {
    // 进入编辑模式
    isEdit.value = true;
  }
};

// 保存编辑
const handleSaveEdit = async () => {
  if (!memberId.value) return;
  
  try {
    uni.showLoading({ title: '保存中...' });
    await updateMember(memberId.value, editForm);
    uni.showToast({ title: '保存成功' });
    isEdit.value = false;
    await getMemberDetail();
  } catch (error: any) {
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 处理头像点击
const handleAvatarClick = () => {
  if (!isEdit.value) return;
  
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 这里可以上传头像到服务器
      console.log('选择的头像:', res.tempFilePaths[0]);
      uni.showToast({ title: '头像上传功能待实现' });
    }
  });
};

// 处理调整余额
const handleAdjustBalance = () => {
  balanceForm.type = 'add';
  balanceForm.amount = '';
  balanceForm.description = '';
  balancePopupRef.value?.open();
};

// 确认调整余额
const confirmAdjustBalance = async () => {
  try {
    await balanceFormRef.value?.validate();
    
    const amount = parseFloat(balanceForm.amount);
    const actualAmount = balanceForm.type === 'add' ? amount * 100 : -amount * 100;
    
    uni.showLoading({ title: '调整中...' });
    await adjustMemberBalance(memberId.value!, actualAmount, balanceForm.description);
    
    uni.showToast({ title: '余额调整成功' });
    balancePopupRef.value?.close();
    await getMemberDetail();
  } catch (error: any) {
    uni.showToast({
      title: error.message || '调整失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 关闭余额弹窗
const closeBalancePopup = () => {
  balancePopupRef.value?.close();
};

// 处理调整积分
const handleAdjustPoints = () => {
  pointsForm.type = 'add';
  pointsForm.points = '';
  pointsForm.description = '';
  pointsPopupRef.value?.open();
};

// 确认调整积分
const confirmAdjustPoints = async () => {
  try {
    await pointsFormRef.value?.validate();
    
    const points = parseInt(pointsForm.points);
    const actualPoints = pointsForm.type === 'add' ? points : -points;
    
    uni.showLoading({ title: '调整中...' });
    await adjustMemberPoints(memberId.value!, actualPoints, pointsForm.description);
    
    uni.showToast({ title: '积分调整成功' });
    pointsPopupRef.value?.close();
    await getMemberDetail();
  } catch (error: any) {
    uni.showToast({
      title: error.message || '调整失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 关闭积分弹窗
const closePointsPopup = () => {
  pointsPopupRef.value?.close();
};

// 导航到余额记录
const navigateToBalanceLog = () => {
  if (!memberId.value) return;
  uni.navigateTo({
    url: `/pages/members/balance-log?memberId=${memberId.value}`
  });
};

// 导航到积分记录
const navigateToPointsLog = () => {
  if (!memberId.value) return;
  uni.navigateTo({
    url: `/pages/members/points-log?memberId=${memberId.value}`
  });
};

// 导航到会员卡管理
const navigateToMemberCard = () => {
  if (!memberId.value) return;
  uni.navigateTo({
    url: `/pages/members/card?memberId=${memberId.value}`
  });
};

// 处理状态管理
const handleStatusManagement = () => {
  const actions = ['正常', '禁用'];
  uni.showActionSheet({
    itemList: actions,
    success: async (res) => {
      const newStatus = res.tapIndex === 0 ? 1 : 0;
      if (newStatus !== memberInfo.value.status) {
        try {
          uni.showLoading({ title: '更新中...' });
          await updateMember(memberId.value!, { status: newStatus });
          uni.showToast({ title: '状态更新成功' });
          await getMemberDetail();
        } catch (error: any) {
          uni.showToast({
            title: error.message || '状态更新失败',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

onLoad((options: any) => {
  if (options.id) {
    memberId.value = parseInt(options.id);
  }
});

onShow(() => {
  if (memberId.value) {
    getMemberDetail();
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.content-scroll {
  flex: 1;
  height: 0;
}

.member-info-card {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.avatar-section {
  display: flex;
  justify-content: center;
  position: relative;
  
  .member-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    border: 3px solid #e0e0e0;
  }
  
  .avatar-edit-btn {
    position: absolute;
    bottom: 0;
    right: calc(50% - 50px);
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: #2979FF;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 40px;
  
  .info-label {
    font-size: 14px;
    color: #666;
    width: 80px;
    flex-shrink: 0;
  }
  
  .info-value {
    flex: 1;
    font-size: 14px;
    color: #333;
    text-align: right;
  }
  
  .level-display,
  .status-display {
    flex: 1;
    display: flex;
    justify-content: flex-end;
  }
}

.balance-points-section {
  display: flex;
  gap: 0;
  margin: 0 15px;
  
  .balance-card,
  .points-card {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    padding: 10px 0;
    
    .amount-display {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 5px;
      
      .amount-value {
        font-size: 20px;
        font-weight: bold;
        color: #2979FF;
      }
      
      .amount-label {
        font-size: 12px;
        color: #999;
      }
    }
    
    .adjust-btn {
      margin: 0;
      padding: 0 15px;
      font-size: 12px;
    }
  }
}

.function-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding: 10px 0;
  
  .function-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    padding: 20px 10px;
    background-color: #f8f9fa;
    border-radius: 8px;
    
    .function-text {
      font-size: 14px;
      color: #333;
    }
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 10px 0;
  
  .stat-item {
    display: flex;
    flex-direction: column;
    gap: 5px;
    
    .stat-label {
      font-size: 12px;
      color: #999;
    }
    
    .stat-value {
      font-size: 14px;
      color: #333;
    }
  }
}

.adjust-popup-content {
  padding: 20px 0;
  
  .current-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 20px;
    
    .current-label {
      font-size: 14px;
      color: #666;
    }
    
    .current-value {
      font-size: 16px;
      font-weight: bold;
      color: #2979FF;
    }
  }
  
  .adjust-form {
    .uni-forms-item {
      margin-bottom: 15px;
    }
  }
}
</style>